package com.redisson.controller;

import com.redisson.compoent.lock.RedisLock;
import com.redisson.compoent.rateLimit.RedisRateLimiter;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RFuture;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@RestController
public class RedissonController {
    @Autowired
    private RedisLock redisLock;
    @Autowired
    private RedisRateLimiter redisRateLimiter;

    @Autowired
    private RedissonClient redisson;

    static int n=0;

    @RequestMapping("test")
    public String testLock() throws InterruptedException {
        n=n+1;
        System.out.println(n+"  test："+System.currentTimeMillis()+" "+UUID.randomUUID());
        RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch"+ UUID.randomUUID());
        latch.trySetCount(1);
        latch.await(15, TimeUnit.SECONDS);
        System.out.println("teste："+System.currentTimeMillis());
        return "success";
    }

    @RequestMapping("test2")
    public String testLock2() throws ExecutionException, InterruptedException {
//        RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch");
//        latch.countDown();
//        System.out.println("test2："+System.currentTimeMillis());

//
//        RLock lock=redisson.getLock ( "myLock" );
//        String str=null;
//        try {
//            if (lock.tryLock ()){
//                System.out.println ("拿到了锁");
//                Thread.sleep(5000l);
//                System.out.println ("拿到了锁");
//
//            }else{
//                System.out.println ("没有拿到锁");
//            }
//
//        } catch (InterruptedException e) {
//            System.out.println ("InterruptedException");
//        } finally {
//            lock.unlock();
//        }


        RLock lock = redisson.getLock("Expor2");


        try {



            if (lock.tryLock()) {
                System.out.println("处理一下1逻辑" + n);
                Thread.sleep(3000l);
                n = n + 1;
                System.out.println("处理一下2逻辑" + n);
            } else {
                System.out.println ("排队中,请稍后重试!");
            }

        } catch (Exception  e) {
            System.out.println("请勿重复操作!");
        } finally {

            try {
                lock.unlock();

            } catch (Exception  e){
        }
        }
        System.out.println("结束了");



        return "success";
    }

    @RequestMapping("testLimit")
    public String testLimit(){
        for (int i = 0; i < 100; i++) {
            redisRateLimiter.limitRate("testLimit");
        }
        return "success";
    }
}
